package com.example.rbm;

import com.example.pojo.entity.Post;
import com.example.service.SendEmailService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.example.consts.RbmConsts.MESSAGE_QUEUE;

/**
 * 本文来演示
 *
 * @author 赵建云
 * @create 2023/10/12
 */
@Component
public class RbmSendEmailService {
    @Autowired
    private SendEmailService sendEmailService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitHandler
    @RabbitListener(queues = MESSAGE_QUEUE)
    public void sendEmail(String msg, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG)long tag) throws IOException {
        int count = 5;
        boolean flag = false;
        SetOperations sop = redisTemplate.opsForSet();
        String uuid = UUID.randomUUID().toString();
        while (!flag&&(count--)>0){
            try {
                if (sop.pop(uuid)!=null){
                    System.out.println("已经被消费过");
                    channel.basicAck(tag,false);
                    return;
                }
                String to = "3469978091@qq.com";
                String subject = "职途万里提醒您，您关注的职位有新的发布";
                String content = msg;
                sendEmailService.sendEmail(to,subject,content);
                flag = true;
                sop.add(uuid,1, TimeUnit.SECONDS,10);
                channel.basicAck(tag,false);
            } catch (IOException e) {
                System.out.println("重试发送");
            }

            if (!flag){
                channel.basicNack(tag,false,false);
            }

        }

    }
}
